package com.peng.controller;

import com.peng.domain.ResponseResult;
import com.peng.domain.dto.ChangeStatusDto;
import com.peng.domain.dto.ChangeUserStatusDto;
import com.peng.domain.entity.Role;
import com.peng.domain.entity.User;
import com.peng.domain.vo.PageVo;
import com.peng.domain.vo.UserInfoAndRoleIdsVo;
import com.peng.service.RoleService;
import com.peng.service.UserService;
import com.peng.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/system/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @GetMapping("/list")
    public ResponseResult getUserList(Integer pageNum, Integer pageSize, User user) {
        PageVo pageVo = userService.getPageList(pageNum, pageSize, user);
        return ResponseResult.okResult(pageVo);
    }

    @PostMapping()
    public ResponseResult addUser(@RequestBody User user){
     return userService.addUser(user);
    }

    @DeleteMapping("/{id}")
    public ResponseResult delete(@PathVariable("id") List<Long> ids){
        if (ids.contains(SecurityUtils.getUserId())){
            return ResponseResult.errorResult(500,"不能删除正在使用的用户");
        }
        userService.removeByIds(ids);
        return ResponseResult.okResult();
    }
    @GetMapping("/{id}")
    public ResponseResult getList(@PathVariable("id") Long id){
        List<Role> roles = roleService.listAllRole();
        User user = userService.getById(id);
        // 当前用户所具有的角色id列表
        List<Long> roleIds = roleService.slectRoleIdByUserId(id);
        UserInfoAndRoleIdsVo vo = new UserInfoAndRoleIdsVo(user,roles,roleIds);
        return ResponseResult.okResult(vo);
    }

    @PutMapping()
    public ResponseResult edit(@RequestBody User user){
        userService.edit(user);
        return ResponseResult.okResult();
    }
    @PutMapping("/changeStatus")
    public ResponseResult changeStatus(@RequestBody ChangeUserStatusDto changeStatusDto) {
        User user = new User();
        user.setId(changeStatusDto.getUserId());
        user.setStatus(changeStatusDto.getStatus());
        return ResponseResult.okResult(userService.updateById(user));
    }
}
